package duyd.ws.training.web.restful.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import duyd.ws.training.domain.Contact;
import duyd.ws.training.domain.Contacts;
import duyd.ws.training.service.ContactService;

@Controller
@RequestMapping(value = "/contact")
public class ContactController {
	final Logger logger = LoggerFactory.getLogger(ContactController.class);

	@Autowired
	private ContactService contactService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public Contacts listContact() {
		logger.info("Find all contacts");
		return new Contacts(contactService.findAll());
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Contact findContactById(@PathVariable Long id) {
		logger.info("Find contact by id: " + id);
		return contactService.findById(id);
	}

	@RequestMapping(value = { "/", "/{id}" }, method = { RequestMethod.PUT,
			RequestMethod.POST })
	@ResponseBody
	public Contact save(@RequestBody @Valid Contact contact) {
		logger.info("Contact saved/updated successfully" + contact);
		return contactService.save(contact);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public void delete(@PathVariable Long id) {
		logger.info("Deleting contact with id: " + id);
		Contact contact = contactService.findById(id);
		contactService.delete(contact);
		logger.info("Contact deleted successfully: " + contact);
	}

	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	@ResponseBody
	public Contacts listContactWithDetails() {
		logger.info("Find all contacts with detail");
		return new Contacts(contactService.findAllWithDetail());
	}

}
